<?php

// +----------------------------------------------------------------------
// | Author: pp <124910168@qq.com>
// +----------------------------------------------------------------------


namespace controller;

use think\Controller;
use think\Db;
use think\db\Query;
use think\Request;
use service\SmsService;
use service\DataService;
use service\ToolsService;

/**
 * 后台权限基础控制器
 * Class BasicAdmin
 * @package controller
 */
class BasicAdmin extends Controller
{

    /**
     * 页面标题
     * @var string
     */
    public $title;

    /**
     * 默认操作数据表
     * @var string
     */
    public $table;

    /**
     * 系统用户
     * @var string
     */
    public $conSU;
    public $SystemUser = 'SystemUser';
    public $Area = 'Area';
    public $Nation = 'Nation';
    public $Disease = 'Disease';
    public $Patient = 'Patient';
    public $Drugcate = 'Drugcate';
    public $Characteristic = 'Characteristic';
    public $SU;
    public $AR;
    public function _initialize()
    {
        parent::_initialize();
        //站点状态验证
        // $this->_chk_domain();
        $this->conSU = config('dbx.SU');
        $this->SU = Db::connect($this->conSU)->name($this->SystemUser);
        $this->AR = Db::connect($this->conSU)->name($this->Area);

        //民族+疾病
        $this->nationList = Db::name('Nation')->where(['status' => 1, 'is_deleted' => 0])->order('sort asc')->select();
        $this->assign('nationList', $this->nationList);
        
        $this->diseaseList = Db::name('Disease')->where(['status' => 1, 'is_deleted' => 0])->order('sort asc')->select();
        $this->assign('diseaseList', $this->diseaseList);
  
        $this->aid = session('user.aid') ? session('user.aid') : 1;
        $this->areas = $this->AR->order('area_id asc')->select();
        $this->aids = ToolsService::getArrSubIds($this->areas, $this->aid, 'area_id', 'area_parent_id');//当前区域下地区Ids
        // $areaList = $this->_getAreaTrees('Area', ['area_open' => $this->aid, 'area_id' => ['in', $this->aids]]);
        $areaList = $this->_getAreaTrees('Area');
        $this->assign('areaList', $areaList);
        // halt($areaList);
        
        //多选地区
        $this->newareas = $this->AR->where(['area_open' => 1, 'area_parent_id' => 0])->field('area_id as value, area_name as name')->order('area_sort asc')->select();
        // $newareas = ToolsService::arr2subs($this->newareas);
        // $this->assign('newareas', $newareas);
        
        $this->newnations = Db::name('Nation')->where(['status' => 1, 'is_deleted' => 0])->field('id as value, title as name')->order('sort asc')->select();
        $this->assign('newnations', $this->newnations);
        
        $this->newdiseases = Db::name('Disease')->where(['status' => 1, 'is_deleted' => 0])->field('id as value, title as name')->order('sort asc')->select();
        $this->assign('newdiseases', $this->newdiseases);
        // halt($this->newnations);

        $usergroup = config('dbx.member_auth');
        $this->assign('rlist',$usergroup);
    }

    public function __construct(Request $request = null)
    {
        parent::__construct($request);

        // 判断登录状态 直接跳转到登录页面
        if (request()->path() == 'admin' && !session('user')) {
            $this->redirect(url('@admin/login'));
        }

        // $mod = strtolower(request()->controller());
        // $act = strtolower(request()->action());
        // $ifm = db()->query("show tables like '$mod'");
        // halt($ifm);
        // if($ifm){
            // $this->redirect(url('admin/empty_controller/index')."?mod=$mod");
        //     $this->redirect(url('/').'admin.html#/admin/empty/index.html?spm='.$this->request->param('spm'));
        // }
    }

    //站点验证
    public function _chk_domain(){        
        $domain = request()->domain();
        $new_domain = substr($domain, 7);
        $chk = get_domain('domain', $new_domain);
        if(!$chk['status']){
            echo("找不到站点，请联系管理员");die;
        }
        if($chk['status'] == 0){
            echo("站点已关闭，请联系管理员");die;
        }
    }

    /**
     * 表单默认操作
     * @param Query $dbQuery 数据库查询对象
     * @param string $tplFile 显示模板名字
     * @param string $pkField 更新主键规则
     * @param array $where 查询规则
     * @param array $extendData 扩展数据
     * @return array|string
     */
    protected function _form($dbQuery = null, $tplFile = '', $pkField = '', $where = [], $extendData = [])
    {
        $db = is_null($dbQuery) ? Db::name($this->table) : (is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery);
        $pk = empty($pkField) ? ($db->getPk() ? $db->getPk() : 'id') : $pkField;
        $pkValue = $this->request->request($pk, isset($where[$pk]) ? $where[$pk] : (isset($extendData[$pk]) ? $extendData[$pk] : null));
        // 非POST请求, 获取数据并显示表单页面
        if (!$this->request->isPost()) {
            $vo = ($pkValue !== null) ? array_merge((array)$db->where($pk, $pkValue)->where($where)->find(), $extendData) : $extendData;
            if (false !== $this->_callback('_form_filter', $vo)) {
                empty($this->title) || $this->assign('title', $this->title);
                return $this->fetch($tplFile, ['vo' => $vo]);
            }
            return $vo;
        }
        // POST请求, 数据自动存库
        $data = array_merge($this->request->post(), $extendData);
        if (false !== $this->_callback('_form_filter', $data)) {
            $result = DataService::save($db, $data, $pk, $where);
            if (false !== $this->_callback('_form_result', $result)) {
                if ($result !== false) {
                    $this->success('恭喜, 数据保存成功!', '');
                }
                $this->error('数据保存失败, 请稍候再试!');
            }
        }
    }

    /**
     * 列表集成处理方法
     * @param Query $dbQuery 数据库查询对象
     * @param bool $isPage 是启用分页
     * @param bool $isDisplay 是否直接输出显示
     * @param bool $total 总记录数
     * @param array $result
     * @return array|string
     */
    protected function _list($dbQuery = null, $isPage = true, $isDisplay = true, $total = false, $result = [], $pkField = 'id', $sortField = 'sort')
    {
        $db = is_null($dbQuery) ? Db::name($this->table) : (is_string($dbQuery) ? Db::name($dbQuery) : $dbQuery);
        // 列表排序默认处理
        if ($this->request->isPost() && $this->request->post('action') === 'resort') {
            $data = $this->request->post();
            unset($data['action']);
            foreach ($data as $key => &$value) {
                if (false === $db->where($pkField, intval(ltrim($key, '_')))->setField($sortField, $value)) {
                    $this->error('列表排序失败, 请稍候再试');
                }
            }
            $this->success('列表排序成功, 正在刷新列表', '');
        }
        // 列表数据查询与显示
        if (null === $db->getOptions('order')) {
            $fields = $db->getTableFields($db->getTable());
            in_array($sortField, $fields) && $db->order($sortField.' asc');
        }
        if ($isPage) {
            $rows = intval($this->request->get('rows', cookie('rows')));
            cookie('rows', $rows >= 10 ? $rows : 20);
            $page = $db->paginate($rows, $total, ['query' => $this->request->get('', '', 'urlencode')]);
            list($pattern, $replacement) = [['|href="(.*?)"|', '|pagination|'], ['data-open="$1"', 'pagination pull-right']];
            list($result['list'], $result['page']) = [$page->all(), preg_replace($pattern, $replacement, $page->render())];
        } else {
            $result['list'] = $db->select();
        }
        !empty($this->title) && $this->assign('title', $this->title);
        if (false !== $this->_callback('_data_filter', $result['list']) && $isDisplay) {
//            !empty($this->title) && $this->assign('title', $this->title);
            return $this->fetch('', $result);
        }
        return $result;
    }

    /**
     * 列表ajax获取数据方法
     * @param null $db 数据库查询对象
     * @param int $page 页码
     * @param int $size 数量
     * @return \think\response\Json
     */
    protected function _ajaxData($db = null,$searchArray = [], $page = 1, $size = 20) {

        if (is_null($db)) {
            $db = Db::name($this->table);
        } elseif (is_string($db)) {
            $db = Db::name($db);
        }

        $page = $this->request->param('page', $page);
        $size = $this->request->param('limit', $size);

        $get = $this->request->get();
        // 搜索
        if ($searchArray) {
            $keyArr = !empty($get['key']) ? $get['key'] : [];
            foreach ($searchArray as $key) {

                if (isset($keyArr[$key]) && $keyArr[$key] !== '') {
                    $db->where($key, 'like', "%{$keyArr[$key]}%");
                }
            }
        }

        $data = $db->page($page, $size)->select();
        $count = $db->count();

        $result = [
            'code' => 0,
            'count' => $count,
            'data' => $data,
            'msg' => '获取数据成功'
        ];

        return json($result);
    }

    /**
     * 当前对象回调成员方法
     * @param string $method
     * @param array|bool $data
     * @return bool
     */
    protected function _callback($method, &$data)
    {
        foreach ([$method, "_" . $this->request->action() . "{$method}"] as $_method) {
            if (method_exists($this, $_method) && false === $this->$_method($data)) {
                return false;
            }
        }
        return true;
    }

    //短信发送
    public function _sendSms($phone, $log_msg){        
            $sms = new SmsService();
            return $sms->smsBao($phone, $log_msg);
    }
    
    //地区节点（带上下级）
    public function _getAreaTrees($table = 'Area', $where = ['area_open' => 1]) {
        $_menus = Db::connect($this->conSU)->name($table)->where($where)->order('area_sort asc,area_id asc')->select();

        $menus = ToolsService::arr2table($_menus,'area_id','area_parent_id');
        foreach ($menus as $key => &$menu) {

            if (substr_count($menu['path'], '-') > 4) {
                unset($menus[$key]);
                continue;
            }
            if (isset($vo['area_parent_id'])) {
                $current_path = "-{$vo['area_parent_id']}-{$vo['area_id']}";
                if ($vo['area_parent_id'] !== '' && (stripos("{$menu['path']}-", "{$current_path}-") !== false || $menu['path'] === $current_path)) {
                    unset($menus[$key]);
                }
            }
        }
        return $menus;
    }
    
    //站点模板节点（带上下级）
    public function _getTempTrees() {
        $_menus = Db::name($this->tempTreeTable)->select();

        $menus = ToolsService::arr2table($_menus,'id');
        foreach ($menus as $key => &$menu) {

            if (substr_count($menu['path'], '-') > 3) {
                unset($menus[$key]);
                continue;
            }
            // if (isset($vo['area_parent_id'])) {
            //     $current_path = "-{$vo['area_parent_id']}-{$vo['id']}";
            //     if ($vo['area_parent_id'] !== '' && (stripos("{$menu['path']}-", "{$current_path}-") !== false || $menu['path'] === $current_path)) {
            //         unset($menus[$key]);
            //     }
            // }
        }
        return $menus;
    }

    protected function _getPid($where, $area_parent_id = 1) {
        $list = db::connect(config('dbx.SU'))->name('Area')->where($where)->select();
        $option='<option value="0">请选择</option>';
        if(!$where['area_parent_id'])return $option;
        foreach ($list as $k => $v) {
            $selected = $v['area_id'] != $area_parent_id ? "" : ' selected="selected"';
            $option.='<option value="' . $v['area_id'] . '"' . $selected . '>' . $v['area_name'] . '</option>';
        }
        return $option;
    }

    public function _ajaxGetCity(){
        $where = array('area_parent_id'=>input('id'));
        $data = $this->_getPid($where);
        return json($data);
    }

}
